import React from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  FlatList,
  ImageBackground,
  ActivityIndicator,
  Alert,
  TouchableOpacity,
  DeviceEventEmitter
} from 'react-native';
import IconEntypo from 'react-native-vector-icons/Entypo'
import IconFontAwesome from 'react-native-vector-icons/FontAwesome'
import { inject, observer } from 'mobx-react';
import { Lottery, LotteryItem } from 'react-native-super-lottery';
import Toast from 'react-native-root-toast';

@inject((stores) => {
    return {
        luckStore: stores.rootStore.luckStore
    }
  })
@observer class LuckDrawScreen extends React.Component {
    static navigationOptions = {
        title: '抽奖',
        headerBackTitle: '返回',
        onTransitionEnd: ()=>{ console.warn('导航栏切换结束'); }  // 回调
        
    };
    constructor(props){
		super(props);
        this.state = { 
            isLottering: false,
            dataBack: true,
            timeCount: null
        } 
	}
    componentDidMount() {
        this.props.luckStore.getLuckData();
        this.props.luckStore.getResultList();
    }
    componentWillUnmount(){
        try{
            clearTimeout(this.state.timeCount)
            this.setState({
                isLottering: false
            })
            this.refs.lotteryRef.stop();
            DeviceEventEmitter.emit('Home', {id: 1});
        }catch(e){
            // Alert.alert(
            //     '加载页面报错',
            //     e.message,
            //     [
            //       { text: '关闭' }
            //     ],
            //     { cancelable: false }
            // )
        }
    }
    /**
     * 圆圈样式
     */
    _getColor = (item)=>{
        const now = new Date();
        const startTime = item.start_time.split(':');
            const startTimeArr = [
                now.getFullYear(),
                now.getMonth(),
                now.getDate(),
                startTime[0],
                startTime[1],
                now.getSeconds()
            ]
        if(new Date(...startTimeArr).getTime() < now.getTime()){
            return '#FF7F4B'
        }else {
            return '#101010';
        }
    }
    // _getName = (item) => {
    //     const now = new Date();
    //     if(item.end_time < now.getHours() +':' + now.getMinutes()){
    //         return 'circle'
    //     }else {
    //         return 'circle-o';
    //     }   
    // }
    /**
     * 获取宽度
     */
    _getWidth = () => {
        try{

            let count = 0;
            const now = new Date();
            this.props.luckStore.intervalInfo.forEach((item)=>{
                const startTime = item.start_time.split(':');
                const starTimeArr = [
                    now.getFullYear(),
                    now.getMonth(),
                    now.getDate(),
                    startTime[0],
                    startTime[1],
                    now.getSeconds()
                ]
                if(new Date(...starTimeArr).getTime() < now.getTime()){
                    count ++;
                }
            })
            let width = 33.33 * (count - 1);
            if(count === 0){
                width = 0;
            }
            //如果在中间 + 16.7 
            return width+'%';
        }catch(e){
            // Alert.alert(
            //     '获取宽度报错',
            //     e.message,
            //     [
            //       { text: '关闭' }
            //     ],
            //     { cancelable: false }
            // )
        }
    }
    /**
     * 开始转动
     */
    startLottery = () =>{ 
        try{
            let timeout = null;
            if (!this.state.isLottering) {
                const timeCount = setTimeout(()=>{
                    //二十秒后没有停下来,就直接停下来
                    clearTimeout(timeout);
                    this.stopLottery({id: 7});//没有中奖
                    this.setState({
                        dataBack: true,
                        isLottering: false
                    })
                },15000)
                this.setState({
                    isLottering: true,
                    timeCount: timeCount
                })
                this.props.luckStore.getLuckResult((response)=>{
                    if(response.status !== 10000){
                        Alert.alert(response.message);
                        this.setState({
                            isLottering: false
                        })
                        clearTimeout(timeCount);
                        return;
                    }else {
                        this.refs.lotteryRef.start();
                        if(this.state.dataBack){
                            return;
                        }
                        this.setState({
                            dataBack: true
                        })
                        timeout = setTimeout(()=>{
                            this.stopLottery(response.data)
                        },500)
                    }
                });
                this.setState({
                    dataBack: false
                })
            } else {
                Alert.alert("正在抽奖中，请稍后再试");
            }
        }catch(e){
            // Alert.alert(
            //     '开始抽奖报错',
            //     e.message,
            //     [
            //       { text: '关闭' }
            //     ],
            //     { cancelable: false }
            // )
        }
    }
    /**
     * 停止
     */
    stopLottery = (data) => {
        try{
            const index = this._getIndex(data.id);
            typeof this.refs.lotteryRef.stop === 'function' && this.refs.lotteryRef.stop(index ,()=>{
                if(data.id === 7 || data.id === 8){
                    //没中奖
                    Toast.show('再接再厉',{
                        duration: Toast.durations.LONG,
                        position: Toast.positions.CENTER,
                        shadow: true,
                        animation: true,
                        hideOnPress: true,
                        delay: 10
                    })    
                }else{
                    // 中奖
                    Toast.show('恭喜中奖了 ' + data.prize,{
                        duration: Toast.durations.LONG,
                        position: Toast.positions.CENTER,
                        shadow: true,
                        animation: true,
                        hideOnPress: true,
                        delay: 10
                    })
                    this.props.luckStore.getResultList({page: 1});
                    this.props.luckStore.getLuckData();
                }
                this.setState({
                    isLottering: false
                }) 
            });
        }catch(e){
            // Alert.alert(
            //     '停止抽奖报错',
            //     e.message,
            //     [
            //       { text: '关闭' }
            //     ],
            //     { cancelable: false }
            // )
        }
    }
    /**
     * 获取id
     */
    _getIndex = (id) => {
        let index1 = 0;
        this.props.luckStore.prize.forEach((item,index)=>{
            if(id === item.id){
                index1 = index;
                return;
            }
        })
        return index1;
    }
    /**
     * 抽奖奖项
     */
    _renderItem = (item,index,highLightIndex) =>{
        if (index === 4) {
            // return <LotteryItem key={index + ''} url={url} type="lotteryBtn" index={index} width={100} height={80} lotteryPress={this.startLottery}/>;
            return  <TouchableOpacity onPress={this.startLottery} key={ index + ''} style={[styles.prizeItem, styles.prizeBtn]}>
                        <View style={styles.prizeItem}>
                            <Text style={styles.prizeBtnTxt}>{item.prize}</Text>
                        </View>
                    </TouchableOpacity>
        } else if (index === highLightIndex) {
            // return <LotteryItem key={ index + ''} url={url} type="highLight" index={index} width={100} height={80}/>;
            return  <View type='highLight' style={[styles.prizeItem,styles.prizeHighLight]} key={ index + ''} >
                        <Image source={require('../assets/images/logo.png')} style={styles.prizeImg}/>
                        <Text>{item.prize}</Text>
                    </View>
        } else {
            // return <LotteryItem key={ index + ''} url={url} type="normal" index={index} width={100} height={80}/>;
            return  <View type='normal' style={styles.prizeItem} key={ index + ''} >
                        <Image source={require('../assets/images/logo.png')} style={styles.prizeImg}/>
                        <Text>{item.prize}</Text>
                    </View>
        }
        
    }
    /**
     * 中奖历史
     */
    _renderList = (item) =>{
        return (
            <View style={styles.resultItem} key={new Date().getTime() + ''}>
                <Text>
                    <Text style={styles.c1}>抽奖结果</Text>
                    <Text style={styles.c2}>{item.item.num}</Text>
                </Text>
                <Text style={styles.c1}>
                    {item.item.addtime}
                </Text>
            </View>
        )
    }
    /**
     * 下拉加载更多
     */
    _onEndReached = () =>{
        let  currentPage = this.props.luckStore.page;
        let lastPage = this.props.luckStore.last_page; 
        if(currentPage >= lastPage){
            return;
        }else {
            this.props.luckStore.getResultList({page: (parseInt(currentPage) + 1)});
        }
    }
    render() {        
        return (
        <View style={styles.container}>
            <View style={styles.timeCount}>
                <View style={styles.timeMain}> 
                    {
                        this.props.luckStore.intervalInfo.map((item)=>{
                            return  <View style={styles.circleList} key={item.interval_type  + ''}>
                                        <View style={styles.iconMain}>
                                            <IconFontAwesome name='circle' style={{
                                                fontSize: 14,
                                                color: this._getColor(item)
                                            }}></IconFontAwesome>
                                        </View>
                                        <View style={styles.circleTxtBox}>
                                            <Text style={styles.circleTxt}>{item.start_time}</Text>
                                            <Text style={styles.circleTxt}>{'~' + item.end_time}</Text>
                                        </View>
                                    </View>
                        })
                    }
                </View>
                <View style={styles.bgLine}>
                    <View style={{
                        backgroundColor:'#FF7F4B',
                        width:this._getWidth(),
                        height: 6
                    }}></View>
                </View>
            </View>
            <View style={styles.lottery}>
                <ImageBackground source={require('../assets/images/lottery-bg.png')} style={styles.lotteryBg}>
                    <View style={styles.LotteryBox}>
                        <Lottery
                            ref='lotteryRef'
                            data={this.props.luckStore.prize}
                            renderItem={this._renderItem}
                            defaultLucky={5}
                        />
                    </View>
                </ImageBackground>
            </View>
            <Text style={styles.last}>本次糖果池总量: {this.props.luckStore.banlace}</Text>
            <View style={styles.getRes}>
                <View style={styles.resBox}>
                    <Text style={styles.c1}>抽到糖果</Text>
                    <Text style={styles.c2}>{this.props.luckStore.candyinfo.candy} NSS</Text>
                </View>
                <View style={styles.resBox}>
                    <Text style={styles.c1}>下级分红</Text>
                    <Text style={styles.c2}>{this.props.luckStore.candyinfo.bonus} NSS</Text>
                </View>
            </View>
            <View style={styles.result}>
                <Text style={styles.resultTit}><IconEntypo name='dots-three-vertical'></IconEntypo>抢糖果记录</Text>
                <FlatList
                    style={styles.flatListStyle}
                    data={this.props.luckStore.resultList}
                    renderItem={this._renderList}
                    keyExtractor={(item, index) => index.toString()}
                    onEndReached={this._onEndReached}
                />
            </View>
        </View>
        );
    }
}

const styles = StyleSheet.create({
    container: { 
      padding: 8,
      flexDirection:'column',
      alignContent:'space-around', 
      height:'100%'
    },
    timeCount:{
        position:'relative',
        height: 60
    },
    timeMain:{
        width: 300,
        left: '50%',
        marginLeft: -150,
        position:'absolute',
        top: 4,
        display: 'flex',
        justifyContent:'space-between',
        alignItems:'center',
        flexDirection: 'row',
        zIndex: 3
    },
    bgLine:{
        position:'absolute',
        top: 5,
        width: 300,
        left: '50%',
        marginLeft: -150,
        height: 6,
        backgroundColor: '#f0f0f0',
        borderRadius: 6,
        overflow:'hidden',
        zIndex: 1
    },
    circleList:{
        position: 'relative',
    },
    circleTxtBox:{
        position: 'absolute',
        width: 80,
        marginLeft: -40,
        top: 10
    },
    circleTxt:{
        textAlign:'center'
    },
    iconMain:{
        marginTop: -3,
        backgroundColor:'#ffffff',
        zIndex: 1
    },
    iconCircle:{

    },
    iconActive:{
        color:'#FF7F4B'
    },
    lotteryBg:{
        width: '100%',
        height: 220,
        marginLeft:'auto',
        marginRight: 'auto',
    },
    lottery:{
        paddingTop: 20,
        width: 260,
        marginLeft:'auto',
        marginRight:'auto'
    },
    resultItem:{
        borderBottomColor: '#101010',
        borderBottomWidth: 1,
        display:'flex',
        justifyContent:'space-between',
        flexDirection:'row',
        alignItems:'center',
        height: 50
    },
    LotteryBox:{
        marginTop: 18
    },
    c2:{
        color:'#FF7F4B'
    },
    c1:{
        color:'#101010'
    },
    last:{
        color:'#ff0000',
        marginTop: 20,
        marginBottom: 20,
        textAlign:'center'
    },
    prizeItem:{
        width: 70,
        height: 50,
        backgroundColor:'#fff6d6',
        borderRadius: 5,
        margin: 5,
        display:'flex',
        flexDirection:'column',
        justifyContent:'space-around',
        alignItems:'center'
    },
    prizeImg:{
        width: 40,
        height: 40
    },
    prizeBtn:{
        width: 70,
        height: 50,
        display:"flex",
        alignItems:'center',
        justifyContent:'space-between'
    },
    prizeHighLight:{
        backgroundColor:'rgba(255,246,214,1)'
    },
    result: {
        display:'flex',
        flexDirection: 'column', 
        justifyContent:'space-between',
        flex: 2
    },
    flatListStyle:{
        marginTop: 10
    },
    getRes:{
        display:'flex',
        justifyContent:'space-between',
        flexDirection:'row',
        marginBottom: 10
    },
    resBox:{
        display:'flex',
        flexDirection:'row',
    }
});
export default LuckDrawScreen; 
